﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Storage.Streams;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Devices.Enumeration;

namespace MiPWinRTSDK
{
    static class BluetoothExtensions
    {
        private static IAsyncOperation<T> ReadValueAsync<T>(this DeviceInformation bleDevice, Guid gattServiceUuid, Guid gattCharacteristicUuid) where T : class
        {
            return readValueAsync<T>(bleDevice, gattServiceUuid, gattCharacteristicUuid).AsAsyncOperation();
        }

        public static IAsyncAction WriteValueAsync(this DeviceInformation bleDevice, Guid gattServiceUuid, Guid gattCharacteristicUuid, [ReadOnlyArray()] byte[] data)
        {
            return writeValueAsync(bleDevice, gattServiceUuid, gattCharacteristicUuid, data).AsAsyncAction();
        }

        public static IAsyncOperation<GattCharacteristic> SetUpNotifyAsync(this DeviceInformation bleDevice, Guid gattServiceUuid, Guid gattCharacteristicUuid)
        {
            return setUpNotifyAsync(bleDevice, gattServiceUuid, gattCharacteristicUuid).AsAsyncOperation();
        }

        private static async Task<GattCharacteristic> setUpNotifyAsync(this DeviceInformation bleDevice, Guid gattServiceUuid, Guid gattCharacteristicUuid)
        {
            return await Task.Run<GattCharacteristic>(async () =>
            {
                try
                {

                    var genericAccess = await GattDeviceService.FromIdAsync(bleDevice.Id);
                    var characteristics = genericAccess.GetCharacteristics(gattCharacteristicUuid).FirstOrDefault();
                    if (characteristics != null)
                    {
                        var result = await characteristics.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                        if (result == GattCommunicationStatus.Success)
                        {
                            return characteristics;
                        }
                    }
                }
                catch (Exception ex)
                {

                }
                return null;
            });
        }
        private static async Task<T> readValueAsync<T>(this DeviceInformation bleDevice, Guid gattServiceUuid, Guid gattCharacteristicUuid) where T : class
        {

            var genericAccess = await GattDeviceService.FromIdAsync(bleDevice.Id);
            var characteristics = genericAccess.GetCharacteristics(gattCharacteristicUuid).FirstOrDefault();
            if (characteristics != null)
            {
                var result = await characteristics.ReadValueAsync(BluetoothCacheMode.Uncached);

                if (result.Status == GattCommunicationStatus.Success)
                {
                    byte[] forceData = new byte[result.Value.Length];
                    DataReader.FromBuffer(result.Value).ReadBytes(forceData);
                    if (typeof(T) == typeof(string))
                    {
                        return System.Text.Encoding.UTF8.GetString(forceData, 0, forceData.Length) as T;
                    }
                    return forceData as T;
                }
                else
                {
                    //ShowError
                }
            }
            return null;
        }

        private static async Task writeValueAsync(this DeviceInformation bleDevice, Guid gattServiceUuid, Guid gattCharacteristicUuid, byte[] data)
        {

            var genericAccess = await GattDeviceService.FromIdAsync(bleDevice.Id);
            var characteristics = genericAccess.GetCharacteristics(gattCharacteristicUuid).FirstOrDefault();
            if (characteristics != null)
            {

                GattCommunicationStatus result;
                if (characteristics.CharacteristicProperties == GattCharacteristicProperties.WriteWithoutResponse)
                    result = await characteristics.WriteValueAsync(data.AsBuffer(), GattWriteOption.WriteWithoutResponse);
                else
                    result = await characteristics.WriteValueAsync(data.AsBuffer(), GattWriteOption.WriteWithResponse);
                if (result == GattCommunicationStatus.Success)
                {

                }
                else
                {
                    //ShowError
                }
            }
        }
    }
}
